<template>
  <div class="box">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="getList"
    >
      <div v-if="projectList && projectList.length > 0" style="margin-top: 10px">
        <el-card
          class="box-card"
          shadow="hover"
          v-for="(item, index) in projectList"
          :key="index"
          style="margin: 10px"
        >
          <el-descriptions
            :title="item.orderName"
            :column="1"
            direction="vertical"
          >
            <template slot="extra">
              <van-popover
                placement="bottom-end"
                style="float: right; font-size: x-large;"
                v-model="item.flag"
                trigger="click"
                :actions="actions"
                @select="onSelect($event, item.projectId)"
                @closed="
                  () => {
                    item.flag = false;
                  }
                "
              >
                <template #reference>
                  <i
                    class="el-icon-more"
                    @click.stop="item.flag = true"
                  ></i>
                </template>
              </van-popover>
            </template>
             <el-descriptions-item label="项目归属">
              <label>{{coverData(item.projectType)}}</label>
            </el-descriptions-item>
            <el-descriptions-item label="负责人">
              <label>{{ item.createBy || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="客户名称">
              <label>{{ item.customerName || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="运维人员">
              <label>{{ coverUserId(item.opsUserId) || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="开发人员">
              <label>{{ coverUserId(item.devUserId) || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="应收未收">
              <label>{{ item.awaitCollection || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="应付未付">
              <label>{{ item.accountAmt || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="项目进度">
              <label>{{ coverNumber(item) || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="立项表实施工单（天）">
              <label>{{ item.opsEstimateTaskCount || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="立项表开发工单（天）">
              <label>{{ item.devEstimateTaskCount || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="项目工单(天)">
              <el-button
                size="small"
                type="text"
                @click="toTaskDetailInfo(item.orderId)"
              >
                <label>{{ item.actualTaskCount || "--" }}</label>
              </el-button>
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              <label>{{ item.remark || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              <label>{{ item.createTime || "--" }}</label>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <van-empty description="暂无数据" v-else />
    </van-list>
    <el-button
        type="primary"
        icon="el-icon-edit"
        circle
        class="submitButton"
        @click="toTargetAddOrUpdate('-1')"
    ></el-button>
  </div>
</template>

<script>
import {
  listProject,
  delProject,
} from "@/api/crm/project";

import { getExpertList } from "@/api/crm/expert";

import { Toast } from "vant";
export default {
  name: "Project",
  dicts: ["crm_expert_type"],
  props: {
    queryParams: {
      type: Object,
      default: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        userId: null,
        opsUserId: null,
        devUserId: null,
      },
    },
  },
  data() {
    return {
      showPicker: false,
      // 遮罩层
      loading: true,
      finished: false,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 表单参数
      form: {
        customerId: "",
      },
      // 表单校验
      rules: {},
      expertList: [],
      showPicker: false,
      actions: [
        { text: "修改", icon: "edit" },
        { text: "删除", icon: "delete-o" },
      ],
    };
  },
  created() {
    this.$nextTick(() => {
      this.getList();
      this.getExpertList();
    });
  },
  watch: {
    "form.customerId": {
      handler(val) {
        if (val) this.getOrderByCustomerIdAndProgress();
      },
      deep: true,
    },
  },
  methods: {
    getData(){},
    onSelect(action, projectId) {
      if (action.text === "修改") {
        this.$router.push("/crm/projectAddOrUpdate/" + projectId);
      } else if (action.text === "删除") {
        this.handleDelete(orderId);
      }
    },
    toTargetAddOrUpdate(projectId) {
       this.$router.push("/crm/projectAddOrUpdate/" + projectId);
    },
    coverNumber(row, column, cellValue) {
      row.opsEstimateTaskCount = isNaN(row?.opsEstimateTaskCount)
        ? 0
        : row.opsEstimateTaskCount;

      row.devEstimateTaskCount = isNaN(row?.devEstimateTaskCount)
        ? 0
        : row.devEstimateTaskCount;

      let count = row.opsEstimateTaskCount + row.devEstimateTaskCount;

      const percentage = count === 0 ? 0 : (row.actualTaskCount / count) * 100;
      return Number.isNaN(percentage) || !Number.isFinite(percentage)
        ? "暂无数据"
        : `${percentage.toFixed(2)}%`;
    },
    toTaskDetailInfo(orderId) {
      // this.$router.push({
      //   path: "/crm/project/components/mobile/taskDetails",
      //   query: {
      //     orderId: orderId,
      //     createBy: null,
      //     type: "1",
      //   },
      // });
    },
    coverData(type) {
      switch (type) {
        case "0":
          return "个人";
        case "1":
          return "部门";
        case "2":
          return "小组";
        default:
          return "未知";
      }
    },

    coverUserId(cellValue) {
      if (!cellValue) return "无";
      let userStr = "";
      if (typeof cellValue === "string") {
        cellValue = cellValue.split(",").map(Number);
      }
      let index = 0;
      cellValue.forEach((item) => {
        let name = this.expertList.find(
          (expert) => expert.expertId == item
        )?.expertName;

        userStr += index === 0 ? name : "," + name;
        index++;
      });
      return userStr;
    },
    getExpertList() {
      getExpertList().then((res) => {
        this.expertList = res.data;
      });
    },
    /** 查询项目列表 */
    async getList() {
      this.loading = true;
      try {
        let obj = JSON.parse(JSON.stringify(this.queryParams));
        if (this.queryParams.opsUserId) {
          obj.opsUserId = this.queryParams.opsUserId.join(",");
        }
        if (this.queryParams.devUserId) {
          obj.devUserId = this.queryParams.devUserId.join(",");
        }
        let res = await listProject(obj);
        // 判断是否加载完所有数据
        if (this.projectList.length >= res.total) {
          this.finished = true;
        } else {
          this.projectList.push(
            ...res.rows.map((item) => ({
              ...item,
              flag: false,
            }))
          );
          this.queryParams.pageNum += 1;
        }
      } catch (error) {
        console.error("加载数据失败", error);
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        orderId: null,
        userId: null,
        opsUserId: null,
        devUserId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.projectList = [];
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId;
      this.$modal
        .confirm('是否确认删除项目编号为"' + projectIds + '"的数据项？')
        .then(function () {
          return delProject(projectIds);
        })
        .then(() => {
          this.handleQuery();
          Toast("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/project/export",
        {
          ...this.queryParams,
        },
        `project_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>

.submitButton {
  position: fixed;
  top: 85%;
  left: 85%;
}
.box {
  min-height: 80vh;
}

.el-card {
  border-radius: 15px;
}
.el-card label {
  font-size: 15px;
  color: #514848;
}
::v-deep .el-descriptions__title {
  font-size: 20px;
}

::v-deep .el-descriptions__header {
  margin-bottom: 10px;
}
</style>
